package com.xcf.controller.business.settlement;

import cn.com.xcf.dao.model.*;
import cn.com.xcf.service.CheckCostService;
import cn.com.xcf.service.FeeCheckService;
import cn.com.xcf.service.InvoiceTitleService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.google.common.collect.Lists;
import java.util.Date;
import com.xcf.controller.base.BaseController;
import com.xcf.controller.base.CommonResponse;
import com.xcf.controller.base.ExportDataHandler;
import com.xcf.entity.Page;
import com.xcf.entity.system.User;
import com.xcf.util.DateUtil;
import com.xcf.util.Jurisdiction;
import com.xcf.util.PageData;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * 成本对账
 * @author WongBin
 */
@Controller
@RequestMapping(value="/costAcct")
public class CheckCostController extends BaseController implements ExportDataHandler {
	
	String menuUrl = "/costAcct/index"; //菜单地址(权限用)
    private static final String PREFIX = "/business/settlement/";
	private static final String base = "/business/settlement/";
	@Autowired
	private CheckCostService checkService;

	@RequestMapping(value = "/index")
	public ModelAndView index(Page page, HttpServletRequest req){
		ModelAndView mv = this.getModelAndView();
		mv.setViewName(base.concat("check_cost_index"));
		mv.addObject("pd", new HashMap());
		return mv;
	}
	@RequestMapping(value="/listUndoList",method = RequestMethod.POST)
	public Object getUndoList(Page page, HttpServletRequest req) throws Exception{
		Map param = getParams(req);//new PageData(req);
		TCheckCostExample e = new TCheckCostExample();
		e.createCriteria();
		e.setPage(page);
		handlePageParams(param,e.getPage());
		ModelAndView mv = getModelAndView();
		try{
			List ret = checkService.getCheckUndoList(e,param,e.getPage());
			//PageData pd = getPageData();
			mv.addObject("dataList",ret);
            mv.addObject("formIndex",param.get("formIndex"));
			mv.addObject("page",e.getPage());
			mv.addObject("QX", Jurisdiction.getHC());//按钮权限
			mv.setViewName(base.concat("panel/check_cost_item_left"));
			return mv;
		} catch(Exception ex){
			log.error("query-check-error:"+param,ex);
		}
		return CommonResponse.fail();
	}

	/**
	 * save
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/append",method = RequestMethod.POST)
	@ResponseBody
	public CommonResponse append(
			@RequestParam String checkId,
			@RequestParam String undoList,
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		CommonResponse response = new CommonResponse();
		String operator = getLoginUser(req,res).getUSER_ID();

		try {
			assert undoList!=null && undoList.length()>0 && !StringUtils.isEmpty(checkId);
			List list = Arrays.asList(undoList.split(","));
			checkService.addToCheckList(checkId, list, operator, CheckCostService.CheckCostDetailStatus.CANCEL.getFlag());
			response.initSuccess();
		}catch (Exception ex){
			log.error("append-checklist-error:{}",undoList,ex);
			response.initSysError(ex.getMessage());
		}
		return response;
	}

	/**删除
	 * @throws Exception
	 */
	@RequestMapping(value="/cancel",method = RequestMethod.POST)
	@ResponseBody
	public CommonResponse cancel(@RequestParam Object id,
								 HttpServletRequest req,HttpServletResponse res) throws Exception{
		CommonResponse response = new CommonResponse();
		String operator = getLoginUser(req,res).getUSER_ID();
		try {
			assert id!=null ;
			String keys = id+"";
			for(String item : keys.split(",")) {
				checkService.cancelRecord(Long.valueOf(item), operator);
			}
			response.initSuccess();
		}catch (Exception ex){
			log.error("cacel-checklist-error:{}",id,ex);
			response.initSysError(ex.getMessage());
		}
		return response;
	}
	@RequestMapping(value="/requestPay",method=RequestMethod.POST)
    @ResponseBody
    public CommonResponse requestPay(@RequestParam Object id,
			 HttpServletRequest req,HttpServletResponse res) throws Exception{
		CommonResponse response = new CommonResponse();
		String operaterId = getLoginUser(req,res).getUSER_ID();
		String operaterName = getLoginUser(req,res).getUSERNAME();
		try {
		assert id!=null ;
		String keys = id+"";
		for(String item : keys.split(",")) {
		 checkService.updatePayRecordFlag(Long.valueOf(item), operaterId,operaterName);
		}
		response.initSuccess();
		}catch (Exception ex){
			
		 response.initSysError(ex.getMessage());
		}
		return response;
    }
	/**
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/genCheckRecord",method = RequestMethod.POST)
	@ResponseBody
	public CommonResponse genRecord(
			@RequestParam String undoList,
			@RequestParam String depart,
			@RequestParam String total,
			@RequestParam String requirePayTime,
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		CommonResponse response = new CommonResponse();
		User operator = getLoginUser(req,res);//.getUSER_ID();
		try {
			assert undoList.length()>0;
			operator.setSKIN(depart);
			Map map = getParams(req);
			checkService.genCheckRecord(Arrays.asList(undoList.split(",")),operator,map);
			response.initSuccess();
		}catch (Exception ex){
			log.error("add-checklist-error:{}",undoList,ex);
			response.initSysError(ex.getMessage());
		}
		return response;
	}
	/**
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/getCheckList",method = RequestMethod.POST)
	public Object getCheckList(
			TCheckCost item, Page page,
			HttpServletRequest req, HttpServletResponse res) throws Exception{
		ModelAndView mv = getModelAndView();
		String operator = getLoginUser(req,res).getUSER_ID();
		handlePageParams(getParams(req),page);
		Map param = getParams(req);
		try {
			List data = checkService.getCheckList(item,param,page);
			mv.addObject("checkList",data);
            mv.addObject("formIndex",param.get("formIndex"));
			mv.addObject("page",page);
			mv.addObject("operator",Jurisdiction.getUsername());
			mv.addObject("QX", Jurisdiction.getHC());//按钮权限
			mv.setViewName(base.concat("panel/check_cost_item_rtop"));
		}catch (Exception ex){
			log.error("get-checklist-error:{}",item,ex);
		}
		return mv;
	}
	/**
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/invalid",method = RequestMethod.POST)
	@ResponseBody
	public CommonResponse invalid(
			@RequestParam String checkId,
			@RequestParam String undoList,
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		CommonResponse response = new CommonResponse();
		String operator = getLoginUser(req,res).getUSER_ID();
		try {
			assert checkId!=null && checkId.length()>0 && undoList!=null && undoList.length()>0;
			checkService.invalidCheckRecordDetails(checkId,Arrays.asList(undoList.split(",")),operator);
			response.initSuccess();
		}catch (Exception ex){
			log.error("invalidate-error:{}",undoList,ex);
			response.initSysError(ex.getMessage());
		}
		return response;
	}

	/***
	 * 未生成对账单时，预审核，通过0->2，撤销 2->0, 生成对账单 2->1,费用初始状态 0
	 * @param undoList
	 * @param req
	 * @param res
	 * @return
     * @throws Exception
     */
	@RequestMapping(value="/updateItemStatus",method = RequestMethod.POST)
	@ResponseBody
	public CommonResponse updateItemStatus(
			@RequestParam String status,
			@RequestParam String undoList,
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		CommonResponse response = new CommonResponse();
		String operator = getLoginUser(req,res).getUSER_ID();
		try {
			assert undoList!=null && undoList.length()>0;
			String currStatus = "0";//避免修改旧的数据
			if("2".equals(status)){
				currStatus = "0";
			}
			if("0".equals(status)){
				currStatus = "2";
			}
			checkService.resetItemStatus("-1",Arrays.asList(undoList.split(",")),status,currStatus);
			response.initSuccess();
		}catch (Exception ex){
			log.error("resetItemStatus-error:{}",undoList,ex);
			response.initSysError(ex.getMessage());
		}
		return response;
	}
	@RequestMapping(value="/listItems",method = RequestMethod.POST)
	public ModelAndView listItems(
			@RequestParam String checkId,
			HttpServletRequest req,HttpServletResponse res) throws Exception{
		String operator = getLoginUser(req,res).getUSER_ID();
        Map param = getParams(req);
		ModelAndView view = getModelAndView();
		try {
			assert checkId!=null && checkId.length()>0 /*&& undoList!=null && undoList.length()>0*/;
			Object data = checkService.listItemsByCheckId(checkId);
			view.addObject("data",data);
            view.addObject("formIndex",param.get("formIndex"));
			view.addObject("QX", Jurisdiction.getHC());//
			view.setViewName(base.concat("panel/check_cost_item_rbottom"));
		}catch (Exception ex){
			log.error("list-items-error:{}",checkId,ex);
		}
		return view;
	}

	@Override
	public List getData(String type, Map param, Page page) {
		if("checkCostUndoList".equalsIgnoreCase(type)){
			List ret = checkService.getCheckUndoList(param,new HashMap(1),page);
			return ret;
		}
		if("checkCostList".equalsIgnoreCase(type)){
			TCheckCost item = new TCheckCost();
			List data = checkService.getCheckList(item,param,page);
			return data;
		}
		if("CostBill".equalsIgnoreCase(type)){
			PageData pd = new PageData();
			String USERNAME = Jurisdiction.getUsername();//当前登录的用户名   	
			pd.put("user", USERNAME);
			Date data = new Date();
			SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd");
			String time = format.format(data);
		 PageData pdq = checkService.findInfo(pd);
		 List<Map> ret = checkService.serCostBill(param.get("Exportcostbill").toString());
		 List<Map<String,Object>> map = new ArrayList<Map<String,Object>>(); 
			Map mp = new HashMap<String,Object>();	
		 for (Map mm : ret) {
				if(mm.get("code")!=null){
					 	    
						mp.put("DEPARTMENT_NAME", pdq.getString("DEPARTMENT_NAME"));
						mp.put("time", time);
						mp.put("list", ret);
//						mp.put("list", aa.get("code"));
//						mp.put("list", aa.get("BILL_CODE"));
//						mp.put("list", aa.get("amount"));
						map.add(mp); 
						 return Lists.newArrayList(map);
				}else{
					List<Map> ma = checkService.serCost(param.get("Exportcostbill").toString());
					if(pdq!=null)
					{
						mp.put("DEPARTMENT_NAME", pdq.getString("DEPARTMENT_NAME"));
						mp.put("time", time);
						mp.put("list", ma);
						map.add(mp);
					}
					return Lists.newArrayList(map);
				}
				
			}
		
//		  List<Map<String,Object>> map = new ArrayList<Map<String,Object>>(); 
//			Map mp = new HashMap<String,Object>();	
			
//			mp.put("DEPARTMENT_NAME", pdq.getString("DEPARTMENT_NAME"));
//			mp.put("time", time);
//			mp.put("list", ret);
//			map.add(mp);
//		return Lists.newArrayList(mp);		
		}
		return null;
			
	}

	@Override
	public String getService() {
		return getClass().getSimpleName();
	}

	@Override
	public Map<String, String> setNames() {
		Map m = new HashMap(6);
		m.put("checkCostUndoList","check_cost_undo.xls");
		m.put("checkCostUndoListName","未付款对账成本明细");
		m.put("checkCostUndoListModule",getService());

		m.put("checkCostList","check_cost_done.xls");
		m.put("checkCostListName","成本对账单明细.xls");
		m.put("checkCostListModule",getService());
		
		m.put("CostBill","CostBill.xls");
		m.put("CostBillName","付款成本单("+ DateUtil.getSdfTimes()+").xls");
		m.put("CostBillModule",getService());
		return m;
	}

	@Autowired
	FeeCheckService feeCheckService;
	@RequestMapping(value="/indexReview")
	public ModelAndView listReview(Page page, HttpServletRequest req) throws Exception{
		Map param = getParams(req);//new PageData(req);
		TCheckCostExample e = new TCheckCostExample();
		e.createCriteria();
		e.setPage(page);
		handlePageParams(param,e.getPage());
		ModelAndView mv = getModelAndView();
		try{
			List ret = checkService.getCheckUndoList(e,param,e.getPage());
			//PageData pd = getPageData();
			mv.addObject("dataList",ret);
            mv.addObject("formIndex",param.get("formIndex"));
			mv.addObject("page",e.getPage());
			mv.addObject("QX", Jurisdiction.getHC());//按钮权限

			mv.setViewName(PREFIX.concat("check_cost_index_review"));
		} catch(Exception ex){
			log.error("query-check-error:"+param,ex);
		}
		return mv;
	}

	@Resource
	private InvoiceTitleService invoiceTitleService;
	/**
	 * 修改、添加发票二级页面
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/editReceipt")
	public ModelAndView edit(@RequestParam Object checkId,Page page) throws Exception{

		ModelAndView view = new ModelAndView(PREFIX.concat("receipt_add"));
		view.addObject("checkId",checkId);
		/*InvoiceTitleExample ex = new InvoiceTitleExample();
		ex.createCriteria().andCheckIdEqualTo(Long.valueOf(""+checkId));
		ex.setPage(page);*/
		/*List data = invoiceTitleService.getList(checkId,new HashMap(1),page);
		view.addObject("dataList",data);
		view.addObject("page",page);*/
		TCheckCost data = checkService.selectByPrimaryKey(Long.valueOf(""+checkId));
		view.addObject("data",data);
		return view;
	}

	@RequestMapping(value="/listReceipt")
	public ModelAndView listReceipt(@RequestParam Object checkId,Page page,HttpServletRequest req) throws Exception{

		ModelAndView view = new ModelAndView(base.concat("panel/receipt_add_resultset"));
		view.addObject("checkId",checkId);
		handlePageParams(getParams(req),page);
		/*InvoiceTitleExample ex = new InvoiceTitleExample();
		ex.createCriteria().andCheckIdEqualTo(Long.valueOf(""+checkId));
		ex.setPage(page);*/
		List data = invoiceTitleService.getList(checkId,new HashMap(1),page);
		view.addObject("dataList",data);
		view.addObject("page",page);
		return view;
	}

}
